/*
 * Functions for operating char arrays
 */
#ifndef CM_STR_H_
#define CM_STR_H_

#include <stdlib.h>
#include <string.h>
#include <ctype.h>

/* [FUNC] strncpy_nospace
 * [DESC] Copy data from 'src' to 'dest', at most copy 'len' Bytes
 *        this function will ignore white spaces in 'src', like '\t' ' ' etc.
 *        before calling this function, make sure that there is enough space at 'dest'
 * [RETURN]  Amount of Bytes have been copyed to 'dest'
 */
static inline int strncpy_nospace(char *dest, const char *src, size_t len)
{
	if (dest == NULL || src == NULL )
		return 0;
	size_t i = 0;
	int index = 0;
	while (src[i] != 0 && i < len) {
		if (!isspace((int)src[i]))
			dest[index++] = src[i];
		i++;
	}
	dest[index] = 0;
	return index;
}

/* [FUNC] strstart_with
 * [DESC] Check whether 'buffer' is started with character 'c'.(except white spaces)
 *        Max length of 'buffer' is 'max_len'
 * [RETURN] 1 for true, 0 for false.
 */
static inline int strstart_with(const char *buffer, char c, size_t max_len)
{
	if (buffer == NULL )
		return 0;

	const char *temp = buffer;
	while (*temp != 0 && (temp - buffer < max_len)) {
		if (isspace((int)*temp)) {
			temp++;
		} else {
			if (*temp == c)
				return 1;
			else
				return 0;
		}
	}

	return 0;
}

// TODO 不拷贝而只返回偏移后的指针
static inline char* str_strip_head(char *str)
{
	if (str == NULL )
		return NULL ;

	size_t p = 0;
	size_t len = strlen(str);

	while (p < len && isspace((int)str[p]))
		p++;

	if (p > 0 && p < len) {
		strcpy(str, str + p);
	}

	return str;

}

static inline char* str_strip_tail(char *str)
{
	if (str == NULL )
		return NULL ;

	int l = strlen(str);
	int p = l - 1;
	while (p >= 0 && isspace((int)str[p]))
		p--;

	str[p + 1] = 0;

	return str;
}

static inline char* str_strip_all(char *str)
{
	if (str == NULL )
		return NULL ;

	int len = strlen(str) + 1;
	char *temp = (char *) calloc(1, len);

	len = strncpy_nospace(temp, str, len);

	strncpy(str, temp, len);
	str[len] = 0;

	free(temp);

	return str;
}

#endif /* CM_STR_H_ */
